/**
 * @Author: boqii
 * @Date: 2018-05-29 16:06:20
 * @Last Modified by: pandali
 * @Last Modified time: 2018-06-21 13:34:32
 * 生成md5签名.
 */

import md5 from 'blueimp-md5'

export default class Sign {
  constructor () {
    this.token = '214e1ba0-ce80-42d5-bda8-8e97c8dd7a2c'
  }

  creator (params) {
    if ('Sign' in params) {
      delete params.Sign
    }
    const newParamsWithOrder = this.__sortByAscendingKeys(params)
    const stringToSign = this.__joinValues(newParamsWithOrder) + this.token
    return md5(stringToSign)
  }

  __sortByAscendingKeys (obj) {
    var newObj = {}
    var keys = Object.keys(obj)
    keys = keys.sort(function(a, b) {
      if (a > b) return 1
      if (a === b) return 0
      return -1
    })
    for (var i in keys) {
      newObj[keys[i]] = obj[keys[i]]
    }
    return newObj
  }

  __joinValues (obj) {
    const that = this

    if (Array.isArray(obj)) {
      return obj.map(function(v) {
        return that.__joinValues(v)
      }).join(',')
    } else if (typeof obj === 'object' && typeof obj !== 'undefined') {
      obj = that.__sortByAscendingKeys(obj)
      var objArr = []
      for (var item in obj) {
        objArr.push(that.__joinValues(obj[item]))
      }
      return objArr.join('')
    } else {
      // 其他直接转换成字符串返回
      return String(obj).valueOf()
    }
  }
}
